package com.jjyu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjyu.dao.FeedbackMapper;
import com.jjyu.dao.FriendMapper;
import com.jjyu.dao.PreferenceMapper;
import com.jjyu.dao.UserMapper;
import com.jjyu.entity.User;
import com.jjyu.service.UserService;
import com.jjyu.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private FeedbackMapper feedbackMapper;

    @Autowired
    private PreferenceMapper preferenceMapper;

    @Override
    public User findByUserName(String userName) {
        User user = userMapper.findByUserName(userName);
        return user;
    }

    @Override
    public User findByEmail(String email) {
        Map<String, Object> emailMap = new HashMap<>();
        emailMap.put("email", email);
        List<User> users = userMapper.selectByMap(emailMap);
        if (!CollectionUtils.isEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public User register(String name, String email, String password) {
        String passwordMD5 = Md5Utils.stringToMD5(password);

        int number = userMapper.addUser(name, email, passwordMD5);
        User user = userMapper.findByUserName(name);
        return user;
    }

    @Override
    public boolean deleteUser(User user) {
        //删除所有该user在其他表格中的记录
        // 删除friend中的记录
        Map<String, Object> userIdMap = new HashMap<>();
        userIdMap.put("user_id", user.getUserId());
        friendMapper.deleteByMap(userIdMap);
        feedbackMapper.deleteByMap(userIdMap);
        preferenceMapper.deleteByMap(userIdMap);
        // friend中还有一个user_id是friend_id，需要删除
        userIdMap.clear();
        userIdMap.put("friend_id", user.getUserId());
        friendMapper.deleteByMap(userIdMap);
        userIdMap.clear();
        userIdMap.put("user_id", user.getUserId());
        int i = userMapper.deleteByMap(userIdMap);
        return i > 0;
    }
}
